package com.google.zahra.soap;

import org.terracotta.collections.ClusteredMap;

// import java.util.List;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Vector;

import javax.jws.WebService;

@WebService
public class CrashManager {

  private static ClusteredMap<String, String> crashes = Server.toolkit.getMap("chrome_crashes");

  // private static List<String> hashes =
  // Server.toolkit.getList("chrome_hashes");

  public CrashManager() {
    CrashDumpToDisk disk = new CrashDumpToDisk();
    disk.start();
  }

  public boolean recordCrashDump(final String url, final String dump, final String md5) {
    final String ret = crashes.putIfAbsent(url, dump);
    /*
     * if (md5 != null && md5 != "") { hashes.add(md5); }
     */
    return dump.equalsIgnoreCase(ret);
  }

  public String[] getCrashedUrls() {
    Set<String> s = crashes.keySet();
    String[] ret = new String[s.size()];
    s.toArray(ret);
    return ret;
  }

  public int getCrashedUrlsSize() {
    return crashes.size();
  }

  public String getCrashDump(String url) {
    return crashes.get(url);
  }

  public boolean hasCrash(final String url) {
    return crashes.containsKey(url);
  }

  public void clearCrashes() {
    crashes.clear();
    // hashes.clear();
  }

  class CrashDumpToDisk extends Thread {

    // Must be volatile:
    private volatile boolean stop = false;
    String command;

    @Override
    public void run() {
      while (!stop) {
        
        System.out.println("Dumping 1000 URLS");
        long start = System.currentTimeMillis();
        try {       
          Vector<Entry<String, String>> entries = new Vector<Entry<String, String>>();
          synchronized(crashes) {
            for (int x = 0; x < 1000; x++) {
              Entry<String, String> entry = crashes.getRandomEntry();
              if (entry == null) {
                break;
              }
              entries.add(entry);
              crashes.removeNoReturn(entry.getKey());          
            }
          }
          
          FileWriter fw = new FileWriter("urldumps.txt", true);
          BufferedWriter out = new BufferedWriter(fw);
          for (Entry<String, String> entry : entries) {   
            out.write(entry.getKey()+","+entry.getValue());
            out.newLine();
          }
          out.close();
          fw.close();
        } catch (IOException ex) {
          System.err.println("Error: " + ex.getMessage());
        }
        System.out.println("Finished dumping and it took " + (System.currentTimeMillis() - start) );
        
        try {
          Thread.sleep(15000);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }        
      }

      if (stop) {
        System.out.println("Detected stop");
      }
    }

    public void requestStop() {
      stop = true;
    }

  }
}
